package cat.music.ut.base

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import cat.music.ut.CatApp
import cat.music.ut.component.loading.LoadingDialog
import com.iwdael.immersive.getNavigationBarHeight

/**
 * activity 基类
 */
abstract class BaseActivity<T : ViewBinding> : AppCompatActivity() {
    val sp by lazy { CatApp.getInstance().getSp() }
    private val loadingDialog by lazy { LoadingDialog(this) }
    lateinit var vb: T


    // 抽象方法：用于获取 ViewBinding 实例
    abstract val viewBinding: T

    // 抽象方法：用于初始化数据
    abstract fun initView()
    open fun initData() {}
    open fun iniClick() {}
    open fun observe() {}

    /**
     * 返回键点击事件
     */
    open fun back(): Boolean {
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 获取 ViewBinding 实例并设置为 ContentView
        vb = viewBinding
        setBar()
        setContentView(vb.root)
//        vb.root.findViewById<ImageView>(R.id.iv_back)?.click {
//            if (back())
//                finish()
//        }
        initView()
        // 初始化数据
        initData()
        observe()
        iniClick()
    }

    private fun setBar() {
        val navigationBarHeight = getNavigationBarHeight()
        if (navigationBarHeight == 0) return

        // 适配状态栏 & 底部导航栏
        ViewCompat.setOnApplyWindowInsetsListener(vb.root) { v: View, insets: WindowInsetsCompat ->
            val systemBars =
                insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(0, 0, 0, systemBars.bottom) // 只调整 padding，不破坏沉浸
            insets
        }
    }

    fun setSystemBarTransparent() {
        setTranslucentStatus()
    }

    fun setTranslucentStatus() {
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

        // 移除亮色模式，确保状态栏图标为浅色
        window.decorView.systemUiVisibility =
            window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()

        // 设置状态栏颜色为透明
        window.statusBarColor = Color.TRANSPARENT
    }

    fun setLightStatusBarWithDarkIcons() {
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)

        // 保持全屏布局（如果需要）
        var flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

        // 设置亮色模式，使状态栏图标变为深色（黑色）
        flags = flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR

        window.decorView.systemUiVisibility = flags

        // 设置状态栏颜色为透明（如果你想保持透明效果）
        window.statusBarColor = Color.TRANSPARENT
    }

    fun showLoading() {
        runCatching {
            runOnUiThread {
                if (!loadingDialog.isShowing) {
                    loadingDialog.show()
                }
            }
        }
    }

    fun showLoading(msg: String) {
        runCatching {
            runOnUiThread {
                if (!loadingDialog.isShowing) {
                    loadingDialog.show(msg)
                }
            }
        }
    }

    fun hideLoading() {
        runCatching {
            runOnUiThread {
                if (loadingDialog.isShowing) {
                    loadingDialog.dismiss()
                }
            }
        }
    }

    fun toast(msg: String) {
        runOnUiThread {
            kotlin.runCatching {
                Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun startActivity(cls: Class<*>, block: (Intent) -> Unit = {}) {
        val intent = Intent(this, cls)
        block.invoke(intent)
        startActivity(intent);
    }
}